package com.ensibs.nuitinfo2013.model;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ensibs.nuitinfo2013.JSONParser;
import android.os.StrictMode;

public class Collection extends LinkedList<Topic> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Collection instance = null;
	
	private int conteur;
	
	public static Collection getInstance() {
		if (instance == null){
			instance = new Collection();
		}
		return instance;
	}
	
	private Collection() {
		this.conteur = 0;
		if (android.os.Build.VERSION.SDK_INT > 9) {
		    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy);
		}
		this.addAll(updateTopic());
	}

	public int getConteur() {
		return conteur;
	}
	
	@Override
	public boolean add(Topic topic) {
		topic.setId(conteur);
		conteur++;
		return super.add(topic);
	}
	
	public static Topic getTopicById(int id){
		Topic topicResult = null;
		Iterator<Topic> allTopics = instance.iterator();
        while(allTopics.hasNext()) {
        	Topic topic = (Topic) allTopics.next();
        	if(topic.getId() == id){
        		topicResult = new Topic();
        		topicResult = topic;
        		break;
        	}
        		
         }
        return topicResult;
	}
	
	public static Topic getTopicByTitle(String title){
		Topic topicResult = null;
		Iterator<Topic> allTopics = instance.iterator();
        while(allTopics.hasNext()) {
        	Topic topic = (Topic) allTopics.next();
        	if(topic.getTitre().equalsIgnoreCase(title)){
        		topicResult = topic;
        		break;
        	}
        		
         }
        return topicResult;
	}
	
	private ArrayList<Topic> updateTopic(){
		 ArrayList<Topic> listTopic = new ArrayList<Topic>();
		 JSONParser jParser = new JSONParser();
		 
         // get JSON data from URL
         JSONArray json = jParser.getJSONFromUrl("http://nuitinfo-ensibs-2013.alwaysdata.net/topic");

         for (int i = 0; i < json.length(); i++) {

                 try {
					JSONObject c = json.getJSONObject(i);
	                 Topic topic = new Topic();
	                 topic.setId(c.getInt("id"));
	                 topic.setQuestion(c.getString("content"));
	                 topic.setResolu(Boolean.getBoolean(c.getString("statut")));
	                 topic.setTitre(c.getString("title"));
	                 topic.setReponses(getResponseTopic(topic.getId()));
	                 listTopic.add(topic);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
         }
         return listTopic;
	}
	
	private ArrayList<String > getResponseTopic(int id){
		ArrayList<String> listResponse = new ArrayList<String>();
		 JSONParser jParser = new JSONParser();
		 
        // get JSON data from URL
        JSONArray json = jParser.getJSONFromUrl("http://nuitinfo-ensibs-2013.alwaysdata.net/getReply?id="+id);

        for (int i = 0; i < json.length(); i++) {

                try {
					JSONObject c = json.getJSONObject(i);
	                 listResponse.add(c.getString("content"));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        }
        return listResponse;
	}
	
	public void closeTopic(int id){
		// Create a new HttpClient and Post Header
	    HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost("http://nuitinfo-ensibs-2013.alwaysdata.net/cloturerTopic");
	    try {
	        // Add your data
	        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
	        nameValuePairs.add(new BasicNameValuePair("id", id+""));
	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	        // Execute HTTP Post Request
	        HttpResponse response = httpclient.execute(httppost);    
	    } catch (ClientProtocolException e) {
	        // TODO Auto-generated catch block
	    } catch (IOException e) {
	        // TODO Auto-generated catch block
	    }
	}
	
	public void addReply(int id, String content){
		// Create a new HttpClient and Post Header
	    HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost("http://nuitinfo-ensibs-2013.alwaysdata.net/addReply");
	    try {
	        // Add your data
	        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
	        nameValuePairs.add(new BasicNameValuePair("id", id+""));
	        nameValuePairs.add(new BasicNameValuePair("content", content));
	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	        // Execute HTTP Post Request
	        HttpResponse response = httpclient.execute(httppost);
	    } catch (ClientProtocolException e) {
	        // TODO Auto-generated catch block
	    } catch (IOException e) {
	        // TODO Auto-generated catch block
	    }
	    this.reinit();
	}
	
	private void reinit(){
		this.clear();
		this.addAll(updateTopic());
	}
	
	public boolean createTopic(String title, String content){
		// Create a new HttpClient and Post Header
	    HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost("http://nuitinfo-ensibs-2013.alwaysdata.net/creerTopic");
	    try {
	        // Add your data
	        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
	        nameValuePairs.add(new BasicNameValuePair("title", title));
	        nameValuePairs.add(new BasicNameValuePair("content", content));
	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	        // Execute HTTP Post Request
	        HttpResponse response = httpclient.execute(httppost);
	    } catch (ClientProtocolException e) {
	    	return false;
	    } catch (IOException e) {
	    	return false;
		}
	    this.reinit();
	    return true;
	}
}
